package leetcode.editor.cn.dsa02_linkedlist;
//不使用运算符 + 和 - ，计算两整数 a 、b 之和。
//
// 示例 1: 
//
// 输入: a = 1, b = 2
//输出: 3
// 
//
// 示例 2: 
//
// 输入: a = -2, b = 3
//输出: 1 
// Related Topics 位运算 
// 👍 333 👎 0

public class SumOfTwoIntegers371 {
    public static void main(String[] args) {
        Solution solution = new SumOfTwoIntegers371().new Solution();
        int sum = solution.getSum(2, 3);
        System.out.println("2 + 3 = " + sum);
        int sum2 = solution.getSum(-2, 3);
        System.out.println("-2 + 3 = " + sum2);

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * a^b得到无进位的相加结果
         * a&b得到每一位的进位，进位需要左移一位
         * 将进位和相加结果重复上述步骤，直至进位为0
         */
        public int getSum(int a, int b) {
            /*int sum = a^b;
            int carry = (a&b)<<1;
            if (carry != 0) {
                return getSum(sum, carry);
            }
            return sum;*/
           return b != 0 ? getSum(a^b, (a&b)<<1) : a;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)
}